/**
 * @author Kostya
 */

var iWindow = null;
var iOpener = null;

var iOkButton = null;
var iCancelButton = null;

iNetworkListener = function(aNetwork){
	iOkButton.setDisabled(aNetwork);
	iCancelButton.setDisabled(aNetwork);
}

Ext.onReady(function(){
	var lNoteID = String(window.location).split('=')[1];
	iOpener = Ext.air.NativeWindow.getRootHtmlWindow();
	Ext.QuickTips.init();
	iWindow = window.nativeWindow;
	
	iStatusBar = new Ext.StatusBar({
		defaultText: 'Idle',
		region: 'south'
	});
	
	iOkButton = new Ext.Button({
		text: 'Ok',
		handler: function(){
			var lNoteID = iMainPanel.getSelectionModel().getSelectedNode().id;
			iOpener.iSessionWinReference.afterSelectNote(lNoteID);
			iWindow.close();
		}
	});
	
	iCancelButton = new Ext.Button({
		text: 'Cancel',
		handler: function(){
			iWindow.close();
		}
	});
	
	var iMainPanel = new Ext.tree.TreePanel({
		region: 'center',
		rootVisible: false,
		animate: false,
		enableDD: false,
//		border: false,
		ddAppendOnly: true,
		autoScroll: true,
//		style: 'padding-top: 2px;',
		root: {
			nodeType: 'node',
			id: 'root',
			text: 'Loading...',
			leaf: false
		},
		buttonAlign: 'center',
		buttons: [iOkButton, iCancelButton]
	});
	
	var lLoadingNode = new Ext.tree.TreeNode({
		text: 'Loading, please wait...',
		id: 'no-id',
		leaf: true,
		iconCls: 'img',
		icon: 'ext/resources/images/default/grid/loading.gif',
		nodeType: 'node'
	});
	
	iMainPanel.root.appendChild(lLoadingNode);
	
	iMainPanel.on('dblclick', function(node){
		if(node.id=='no-id')
			return;
		iOpener.iSessionWinReference.afterSelectNote(node.id);
		iWindow.close();		
	});
	
	var lViewport = new Ext.Viewport({
		layout: 'border',
		items: [iStatusBar, {
			region: 'center',
			border: false,
			bodyStyle: 'background-color: #f0f0f0;',
			layout: 'fit',
			items: iMainPanel
		}]
	});
	
	iWindow.visible = true;
	iWindow.activate();
	lViewport.doLayout();
	
	var processNode = function(aParentNode, aXMLNode){
		for(var i = 0; i<aXMLNode.childNodes.length; i++){
			var lXMLNode = aXMLNode.childNodes[i];
			if(lXMLNode.nodeType==1){
				var text = escapeHTML(lXMLNode.getAttribute('text'));
				var node = new Ext.tree.TreeNode({
					text: text,
					id: lXMLNode.getAttribute('id'),
					nodeType: 'node',
					icon: 'im/types/p'+lXMLNode.getAttribute('icon')+'.png',
					iconCls: 'img'
				});
				aParentNode.appendChild(node);
				processNode(node, lXMLNode);
			}
		}
	};
	
	callAPI(iOpener.iSessionRecord.get('server'), 'LoadTree', {
			token: iOpener.iToken
		}, function(aXML){
			
			while(iMainPanel.root.childNodes.length>0){
				iMainPanel.root.childNodes[0].remove();
			}
			processNode(iMainPanel.root, aXML.documentElement);
			var lNode = iMainPanel.getNodeById(lNoteID);
			if(lNode){
				iMainPanel.expandPath(lNode.getPath());
				lNode.expand();				
				lNode.select();
			}
		}, function(){
			iWindow.close();
		}
	);
});
